//
//  AppDelegate.m
//  StoryShow
//
//  Created by CyonLeuMBP on 2017/3/12.
//  Copyright © 2017年 qudiandu.cn. All rights reserved.
//

#import "AppDelegate.h"

    //     ViewControllers
#import "FZNavigationController.h"
#import "FZTabBarController.h"
#import "SRHomePageViewController.h"
#import "SRPersonalCenterViewController.h"
#import "SRClassHomeWorkListViewController.h"

#import "SRLoginManager.h"
#import "SRCommonConstants.h"
#import <SRLoginManagerSDK/FZRefreshTokenService.h>
#import "UIAlertView+SRBlocks.h"
#import "FCUtil.h"
#import "FZUrlSchemesRouter.h"
#import "FZCommonTool.h"

//#import <iflyMSC/IFlyMSC.h>
#import <Bugtags/Bugtags.h>
#import <FZCommonShare.h>
#import "FZMCCacheManager.h"
#import "SingSound/SSOralEvaluatingManager.h"
#import <AudioToolbox/AudioToolbox.h>
#import "RIButtonItem.h"

#import <JPush/JPUSHService.h>

	// iOS10注册APNs所需头文件
#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#import <UserNotifications/UserNotifications.h>
#endif


@interface AppDelegate ()<UITabBarControllerDelegate, UINavigationControllerDelegate>

@property (nonatomic,strong) FZTabBarController *tabBarController;
@property (nonatomic,strong) FZNavigationController *navigationController;
@property (nonatomic,strong) FZNavigationController *navigationController1;
@property (nonatomic,strong) FZNavigationController *navigationController2;

@property (strong, nonatomic) UIAlertView *reloginAlertView;

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    self.window.backgroundColor = [UIColor whiteColor];
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
    [self initNavigation];
		//Required
		//notice: 3.0.0及以后版本注册可以这样写，也可以继续用之前的注册方式
	JPUSHRegisterEntity * entity = [[JPUSHRegisterEntity alloc] init];
	entity.types = JPAuthorizationOptionAlert|JPAuthorizationOptionBadge|JPAuthorizationOptionSound;
	if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
			// 可以添加自定义categories
			// NSSet<UNNotificationCategory *> *categories for iOS10 or later
			// NSSet<UIUserNotificationCategory *> *categories for iOS8 and iOS9
	}
	[JPUSHService registerForRemoteNotificationConfig:entity delegate:nil];
	
    [self initAppInfo:application didFinishLaunchingWithOptions:launchOptions];
    [[FZMCCacheManager defaultManager] parseGuideBook];
    
    [self setupRootTabBarController];
    [self.window makeKeyAndVisible];

    return YES;
}


- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}


- (UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window {
    return UIInterfaceOrientationMaskPortrait;
}

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
    BOOL isUrlDo = [[FZUrlSchemesRouter sharedUrlSchemesRouterManager] handleUrlSchemaMap:url tabcontroller:_tabBarController];
    if (isUrlDo) {
        return YES;
    }
    [SRLoginManager handelOpenURL:url];
    [FZCommonShare handleOpenURL:url];
//    [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:nil];
//    [WXApi handleOpenURL:url delegate:[FZWXPayManager sharedManager]];
    return YES;
}

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
     [JPUSHService registerDeviceToken:deviceToken];
}

- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    NSLog(@"did Fail To Register For Remote Notifications With Error: %@", error);
}

#if __IPHONE_OS_VERSION_MAX_ALLOWED > __IPHONE_7_1
- (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings {
}

- (void)application:(UIApplication *)application handleActionWithIdentifier:(NSString *)identifier forLocalNotification:(UILocalNotification *)notification completionHandler:(void (^)())completionHandler {
}

- (void)application:(UIApplication *)application handleActionWithIdentifier:(NSString *)identifier forRemoteNotification:(NSDictionary *)userInfo
  completionHandler:(void (^)())completionHandler {
}
#endif

    // 自定义：APP未启动时处理推送消息处理（APP未启动时--》APP运行）
- (void)receiveRemoteNotificationForApp:(UIApplication *)application launchingOptionS:(NSDictionary *)launchOptions {
    application.applicationIconBadgeNumber =0;     // 标签
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo{
    
    [self application:application didReceiveRemoteNotification:userInfo fetchCompletionHandler:^(UIBackgroundFetchResult result) {
        
    }];
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    [JPUSHService handleRemoteNotification:userInfo];
	
    AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
    if ( application.applicationState == UIApplicationStateInactive){
        if(userInfo && userInfo[@"type"]){
                //通知处理
            [MobClick event:@"JPushNotifOpened"];
			
		}
        
        BOOL hasParse = [[FZRemoteNotificationParser sharedRemoteNotificationParser] handleRemoteNotification:userInfo tabcontroller:_tabBarController];
        if (!hasParse) {
                //融云通知
            [[FZRemoteNotificationParser sharedRemoteNotificationParser] handleRongYunRemoteNotification:userInfo tabcontroller:_tabBarController];
        }
        
    }else if (application.applicationState == UIApplicationStateActive){
            //通知处理
        [[FZRemoteNotificationParser sharedRemoteNotificationParser] handleRemoteNotificationApplicationStateActive:userInfo];
    }
    
    if (completionHandler) {
        completionHandler(UIBackgroundFetchResultNewData);
    }
}

- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification {
    NSDictionary *userInfo = notification.userInfo;
    [[FZRemoteNotificationParser sharedRemoteNotificationParser] handleRemoteNotification:userInfo tabcontroller:_tabBarController];
    
}


#pragma mark - Init app info

- (void)initAppInfo:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    
    [application registerForRemoteNotifications];
    [application registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert) categories:nil]];
    
        //设置环境
    [SRAPICreater sharedInstance].isTestMode = [[[NSBundle mainBundle] objectForInfoDictionaryKey:@"APITestMode"] boolValue];
    
        //讯飞初始化
        //设置sdk的log等级，log保存在下面设置的工作路径中
//    [IFlySetting setLogFile:LVL_ALL];
//    [IFlySetting showLogcat:NO];//打开输出在console的log开关
//        //设置sdk的工作路径
//    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
//    NSString *cachePath = [paths objectAtIndex:0];
//    [IFlySetting setLogFilePath:cachePath];
    
    SSOralEvaluatingManagerConfig *config = [[SSOralEvaluatingManagerConfig alloc]init];
    config.appKey = @"a133";
    config.secretKey = @"3c6cb028f3e6477ab74acbafbfa7cac2";
    config.vad = YES;
    config.frontTime = 3;
    config.backTime = 3;
    [SSOralEvaluatingManager registerEvaluatingManagerConfig:config];
    [[SSOralEvaluatingManager shareManager]registerEvaluatingType:OralEvaluatingTypeLine];
    
    
		// init Push
		// notice: 2.1.5版本的SDK新增的注册方法，改成可上报IDFA，如果没有使用IDFA直接传nil
		// 如需继续使用pushConfig.plist文件声明appKey等配置内容，请依旧使用[JPUSHService setupWithOption:launchOptions]方式初始化。
	
	BOOL isTestModel = [SRAPICreater sharedInstance].isTestMode;
	[JPUSHService setupWithOption:launchOptions appKey:kJPushAPPKey
						  channel:@"APPStore"
				 apsForProduction:!isTestModel
			advertisingIdentifier:nil];
	
        //初使bugtags
    BugtagsOptions *bugOptions = [[BugtagsOptions alloc] init];
    bugOptions.trackingCrashes = YES;
    if ([SRAPICreater sharedInstance].isTestMode) {
        bugOptions.version = @"1.4.0_build1";
    }
    
    [Bugtags startWithAppKey:kBugTagsAppKey invocationEvent:BTGInvocationEventNone options:bugOptions];
    [self initShareView];
    [self initUMeng];
}

/**
 *  初使分享主件
 */
- (void)initShareView
{
        //初始化工作---------------------begin--------------------
        //step 1 注册应用appID
    [[FZCommonShare sharedInstance] setAppkey:kWechatAPPKey type:FZCommonShareWeChat];
    [[FZCommonShare sharedInstance] setAppkey:kSinaAppKey type:FZCommonShareWeibo];
    [[FZCommonShare sharedInstance] setAppkey:kQQAPPID type:FZCommonShareQQ];
        //step 2 初始化UI接口
    [[FZCommonShare sharedInstance] initShareView];
}

/**
 *  初始化百度统计SDK
 */
//- (void)initBaiduMobStat {
//    /*若应用是基于iOS 9系统开发，需要在程序的info.plist文件中添加一项参数配置，确保日志正常发送，配置如下：
//     NSAppTransportSecurity(NSDictionary):
//     NSAllowsArbitraryLoads(Boolen):YES
//     详情参考本Demo的BaiduMobStatSample-Info.plist文件中的配置
//     */
//    BaiduMobStat* statTracker = [BaiduMobStat defaultStat];
//        // 此处(startWithAppId之前)可以设置初始化的可选参数，具体有哪些参数，可详见BaiduMobStat.h文件，例如：
//    statTracker.shortAppVersion  = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
//    statTracker.adid = [FZCommonTool IDFAString];
//    [statTracker startWithAppId:@"appkey"]; // 设置您在mtj网站上添加的app的appkey,此处AppId即为应用的appKey
//}

/**
 *  初始化友盟
 */
-(void)initUMeng{
    UMAnalyticsConfig *config = [UMAnalyticsConfig sharedInstance];
    config.appKey = kUmengAPPKey;
//    config.secret
    config.channelId = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"channelID"];
    
    [MobClick startWithConfigure:config];
    [MobClick setAppVersion:APPVersion];
    [MobClick setLogEnabled:NO];
    
    NSString * deviceName = [[[UIDevice currentDevice] name] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSString * mac = [FCUtil macString];
    NSString * idfa = [FZCommonTool IDFAString];
    NSString * idfv = [FCUtil idfvString];
    NSString * urlString = [NSString stringWithFormat:@"http://log.umtrack.com/ping/%@/?devicename=%@&mac=%@&idfa=%@&idfv=%@", kUmengAPPKey, deviceName, mac, idfa, idfv];
    [NSURLConnection connectionWithRequest:[NSURLRequest requestWithURL: [NSURL URLWithString:urlString]] delegate:nil];
}


    //第一次创建
- (void)setupRootTabBarController {

    if(!self.tabBarController){
        SRHomePageViewController *homeViewController = [[SRHomePageViewController alloc] init];
        [self setTabTitle:@"首页" selectedTabImage:@"bar_icon_home" unSelectedTabImage:@"bar_icon_home_gray" toViewController:homeViewController];
        
        SRPersonalCenterViewController *personalCenterVC = [[SRPersonalCenterViewController alloc] init];
        [self setTabTitle:@"我" selectedTabImage:@"bar_icon_my" unSelectedTabImage:@"bar_icon_my_gray" toViewController:personalCenterVC];
        SRClassHomeWorkListViewController *hkVC = [[SRClassHomeWorkListViewController alloc] init];
        [self setTabTitle:@"班级" selectedTabImage:@"bar_icon_classChooes" unSelectedTabImage:@"bar_icon_classUnchooes" toViewController:hkVC];
        
        self.navigationController = [[FZNavigationController alloc]  initWithRootViewController:homeViewController];
        self.navigationController1 = [[FZNavigationController alloc]  initWithRootViewController:hkVC];

        self.navigationController2 = [[FZNavigationController alloc]  initWithRootViewController:personalCenterVC];
        
        self.tabBarController = [[FZTabBarController alloc] init];
        self.tabBarController.delegate = self;
        self.tabBarController.viewControllers = @[self.navigationController, self.navigationController1, self.navigationController2
                                                  ];
        self.tabBarController.selectedViewController = self.navigationController;
        
        self.navigationController.delegate = self;
        self.navigationController2.delegate = self;
       
        [self.navigationController.navigationBar setTranslucent:YES];
        [self.navigationController2.navigationBar setTranslucent:YES];
  
            // 提前调用“我”页面的viewDidLoad
        UIView * __unused unusedView = personalCenterVC.view;
        UIView * __unused unusedHomePageView = homeViewController.view;
    
    }else{
        [self resetNavigationControllerBar:self.navigationController];
        [self resetNavigationControllerBar:self.navigationController2];
       
        [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
            //切换用户登录发送通知（通知界面刷新）
    }
    
    [[AFNetworkReachabilityManager sharedManager] startMonitoring];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:kPostLogoutNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(shouldReloginNotification:) name:kPostLogoutNotification object:nil];
    
    self.window.rootViewController = self.tabBarController;
}

#pragma mark - Tools Class

- (void)setTabTitle:(NSString *)title selectedTabImage:(NSString *)selectedTabImageName unSelectedTabImage:(NSString *)unSelectedTabImageName toViewController:(UIViewController *)viewController
{
    [viewController.tabBarItem setTitle:title];
    UIImage *selectedTabImage = [UIImage imageNamed:selectedTabImageName];
    UIImage *unSelectedTabImage = [UIImage imageNamed:unSelectedTabImageName];
    UIImage *newSelectedTabImage = [selectedTabImage imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    UIImage *newUnSelectedTabImage = [unSelectedTabImage imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    viewController.tabBarItem.image = newUnSelectedTabImage;
    viewController.tabBarItem.selectedImage = newSelectedTabImage;
    FZStyleSheet *css = [FZStyleSheet currentStyleSheet];
    [viewController.tabBarItem setTitleTextAttributes:@{NSForegroundColorAttributeName:css.tabBarTextColor, NSFontAttributeName:[UIFont systemFontOfSize:P2P(20.0f)]} forState:UIControlStateNormal];
    [viewController.tabBarItem setTitleTextAttributes:@{NSForegroundColorAttributeName:css.tabBarSelectedTextColor, NSFontAttributeName:[UIFont systemFontOfSize:P2P(20.0f)]} forState:UIControlStateSelected];
}

- (void)resetNavigationControllerBar:(UINavigationController*)navigationController{
        //复原
    [navigationController popToRootViewControllerAnimated:NO];
    [navigationController.navigationBar setBackgroundImage:nil forBarMetrics:UIBarMetricsDefault];
    [navigationController.navigationBar setShadowImage:[UIImage imageWithColor:[FZStyleSheet currentStyleSheet].colorOfSeperatorOnLightBackground]];
    navigationController.navigationBar.clipsToBounds = NO;
//    navigationController.navigationBar.titleTextAttributes = nil;
}

- (void)initNavigation
{
    FZStyleSheet *css = [FZStyleSheet currentStyleSheet];
    
    [[UISearchBar appearance] setBackgroundImage:[UIImage imageWithColor:css.colorOfBackground]];
    [[UINavigationBar appearance] setBarTintColor:css.colorOfNavigationBackground];
    [[UINavigationBar appearance] setTintColor:css.colorOfMainTint];
    
    [[UINavigationBar appearance] setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIFont fontWithName:@"Helvetica-Light" size:18], NSFontAttributeName, [UIColor whiteColor], NSForegroundColorAttributeName, nil]];
    
    UIImage *originBackImage = [UIImage imageNamed:@"common_back_gray"];
    UIImage *newBackImage = [originBackImage imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];

    [[UINavigationBar appearance] setBackIndicatorImage:newBackImage];
    [[UINavigationBar appearance] setBackIndicatorTransitionMaskImage:newBackImage];
    
    if (@available(iOS 11.0, *)) {
        //do noth
    } else {
        [[UIBarButtonItem appearance] setBackButtonTitlePositionAdjustment:UIOffsetMake(0, -100) forBarMetrics:UIBarMetricsDefault];
    }
}

- (UIImage *)imageWithImage:(UIImage *)image scaledToSize:(CGSize)newSize {
    UIGraphicsBeginImageContextWithOptions(newSize, NO, 0.0);
    [image drawInRect:CGRectMake(0, 10, newSize.width, newSize.height)];
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}


#pragma mark -- tabbar delegate

- (void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController
{
        //点击老师友盟统计打点
        //------加上的
//    if(self.tabBarController.selectedIndex == 0) {
//        [MobClick event:@"home"];
//    }
//    else if(self.tabBarController.selectedIndex == 3){
//        [MobClick event:@"me"];
//    }
        //--------加上的
    
//    UINavigationController *nav = self.tabBarController.viewControllers[self.tabBarController.selectedIndex];
    
}

#pragma mark -- UINavigationControllerdelegate

- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated
{
        //todo
}

#pragma mark - Login & Public 

- (void)setupLoginViewController {
    WEAKSELF
    [[SRLoginManager sharedManager] showLoginViewControllerFromWindow:self.window showCancelButton:NO success:^{
        [[SRLoginManager sharedManager] uploadJPushRegisterID];
        [weakSelf setupRootTabBarController];
        [[NSNotificationCenter defaultCenter] postNotificationName:SRUserLoginDidChangeNotification object:nil];
        [[NSNotificationCenter defaultCenter] postNotificationName:SRUserLoginDidSuccessNotification object:nil];
    } failure:^(NSString *errorMessage) {
        [[NSNotificationCenter defaultCenter] postNotificationName:SRUserLoginDidFailNotification object:nil];
    } cancel:^{
            //点击返回按钮回到第一个页面
        self.tabBarController.selectedViewController = self.tabBarController.childViewControllers.firstObject;
        self.window.rootViewController = self.tabBarController;
    }];
}


-(void)loginSuccess {
    if ([[SRLoginManager sharedManager] hasLogin]){
        [[NSNotificationCenter defaultCenter] postNotificationName:SRUserLoginDidChangeNotification object:nil];
        [[NSNotificationCenter defaultCenter] postNotificationName:SRUserLoginDidSuccessNotification object:nil];
		
		[[SRLoginManager sharedManager] uploadJPushRegisterID];
    }
}

- (void)logoutAndRelogin:(NSString *)loginTip whetherEnterLoginVC:(BOOL)isEnter{
        //注销消息服务
    [[SRLoginManager sharedManager] logout];
    [SRLoginManager sharedManager].loginTip = loginTip;
    [SRLoginUser setUserID:kSRNotLoginDefaultUserID];
    
    if (self.tabBarController && [self.tabBarController.viewControllers count] > 0) {
        [self.navigationController  popToRootViewControllerAnimated:NO];
        [self.navigationController2  popToRootViewControllerAnimated:NO];
        self.tabBarController.selectedViewController =[self.tabBarController.childViewControllers  objectAtIndex:0];
        if (isEnter) {
                //退出登录并且进入登录页面
            [self setupLoginViewController];
        }
        else {
                //退出登录或者是403错误或者是token过期都会进入我的页面
            self.tabBarController.selectedViewController = self.tabBarController.childViewControllers.lastObject;
            self.window.rootViewController = self.tabBarController;
                //退出登录发送通知，刷新一些界面
            [[NSNotificationCenter defaultCenter] postNotificationName:SRUserLogoutDoneNotification object:nil];
        }
    }
    
}

- (void)showHUDMessage:(NSString *)message {
    
    dispatch_async(dispatch_get_main_queue(), ^{
        MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.window animated:YES];
        hud.mode = MBProgressHUDModeText;
        hud.labelText = message;
        hud.removeFromSuperViewOnHide = YES;
        [hud show:NO];
        [hud hide:NO afterDelay:2];
    });
}

- (void)shouldReloginNotification:(NSNotification *)notification {
    if (![[SRLoginManager sharedManager] currentControllerIsLoginViewController:self.window]) {
        if (!self.reloginAlertView || !self.reloginAlertView.visible) {
            WEAKSELF
            NSString *msg = nil;
            if(notification.object){
                msg = [NSString stringWithFormat:@"%@", notification.object];
                if([msg isEqualToString:@""]){
                    msg = nil;
                }
            }
                //有重新登录的弹框就退出一切服务
                //注销消息服务
            [[SRLoginManager sharedManager] logout];
            [SRLoginUser setUserID:kSRNotLoginDefaultUserID];
            [[NSNotificationCenter defaultCenter] postNotificationName:SRUserLogoutDoneNotification object:nil];
            
            self.reloginAlertView = [[UIAlertView alloc] initWithTitle:@"提示" message:msg?:@"您的帐号已在其它地方登录，请重新登录！" cancelButtonItem:[RIButtonItem itemWithLabel:@"确定" action:^(){ [weakSelf logoutAndRelogin:nil whetherEnterLoginVC:YES];}] otherButtonItems:nil];
            
            [self.reloginAlertView show];
        }
    }
}



@end
